package myzd.services.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import libedge.domain.exceptions.GenericException;
import myzd.api.code.CodeUtils;
import myzd.api.domain.UserIdentity;
import myzd.services.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @author WangLei
 * @since 2017/11/20 14:03
 */
@Component
public class DefaultAuthorizationServiceImpl implements AuthorizationService {

  @Autowired
  private UserIdentity userIdentity;

  @Value("${source.intranet.secret}")
  private String sourceIntranetSecret;

  @Override
  public String createCmsServiceToken() throws GenericException {
    try {
      Algorithm algorithm = Algorithm.HMAC256(sourceIntranetSecret);
      String token = JWT.create()
        .withClaim("role", userIdentity.getRole())
        .withClaim("userName", userIdentity.getName())
        .withClaim("uid", userIdentity.getId())
        .withClaim("department", userIdentity.getDepartmentId())
        .withClaim("user", userIdentity.getEmail())
        .withClaim("reqId", System.currentTimeMillis())
        .withIssuedAt(new Date())
        .sign(algorithm);
      return "Bearer " + token;
    } catch (UnsupportedEncodingException e) {
      throw new GenericException(CodeUtils.ERROR_JWT_TOKEN, CodeUtils.getErrText(CodeUtils.ERROR_JWT_TOKEN));
    }
  }
}
